import math

import torch
import dltools
from torch import nn
import matplotlib.pyplot as plt


# 消除<pad>无意义序列对softmax的影响
def masked_softmax(X, valid_lens):
    # X形状(batch_size, num_steps, vocab_size)
    if valid_lens is None:
        return nn.functional.softmax(X, dim=-1)
    else:
        shape = X.shape
        if valid_lens.dim() == 1:
            valid_lens = torch.repeat_interleave(valid_lens, shape[1])
        else:
            valid_lens = valid_lens.reshape(-1)

        # 给一个非常大的负值进行替换，从而使softmax的输出为0
        X = dltools.sequence_mask(X.reshape(-1, shape[-1]), valid_lens, value=-1e6)
        return nn.functional.softmax(X.reshape(shape), dim=-1)

a = torch.rand(2, 2, 4)
print(a)

res = masked_softmax(a, torch.tensor([2, 3]))
print(res)

# additive attention
class AdditiveAttention(nn.Module):
    def __init__(self, key_size, query_size, num_hiddens, dropout, **kwargs):
        super().__init__(**kwargs)
        self.W_k = nn.Linear(key_size, num_hiddens, bias=False)
        self.W_q = nn.Linear(query_size, num_hiddens, bias=False)
        self.w_v = nn.Linear(num_hiddens, 1, bias=False)
        self.dropout = nn.Dropout(dropout)

    def forward(self, queries, keys, values, valid_lens):
        print(f"queries.shape:{queries.shape}")
        print(f"keys.shape:{keys.shape}")
        queries, keys = self.W_q(queries), self.W_k(keys)
        print(f"----")
        print(f"queries.shape:{queries.shape}")
        print(f"keys.shape:{keys.shape}")
        features = queries.unsqueeze(2) + keys.unsqueeze(1)
        features = torch.tanh(features)
        scores = self.w_v(features).squeeze(-1)
        self.attention_weights = masked_softmax(scores, valid_lens)
        return torch.bmm(self.dropout(self.attention_weights), values)


queries, keys = torch.normal(0, 1, (2, 1, 20)), torch.ones((2, 10, 2))
values = torch.arange(40, dtype=torch.float32).reshape(1, 10, 4).repeat(2, 1, 1)
valid_lens = torch.tensor([2, 6])
attention = AdditiveAttention(key_size=2, query_size=20, num_hiddens=8, dropout=0.1)
attention.eval()
res = attention(queries, keys, values, valid_lens)
print(res)

class DotProductAttention(nn.Module):
    # 缩放点积注意力
    def __init__(self, dropout, **kwargs):
        super().__init__(**kwargs)
        self.dropout = nn.Dropout(dropout)

    def forward(self, queries, keys, values, valid_lens=None):
        # querise的shape：(batch_size, 查询的个数，长度)
        # keys的shape：(batch_size, 健值对的个数，d) 2,10,2
        # valid_lens的shpe: (batch_size), 或者（batch_size, 查询个数）
        d = queries.shape[-1]
        scores = torch.bmm(queries, keys.ranspose(1, 2)) / math.sqrt(d) # 2,1,10
        print(scores.shape)
        self.attention_weights = masked_softmax(scores, valid_lens)
        return torch.bmm(self.dropout(self.attention_weights), values)